<template>
  <div class="container" style="height: 100vh;width: 300px;padding: 20px;box-sizing: border-box;width: 100%;">
    <header>
      <MBreadcrumb :item="breadcrumbItem" />
    </header>
    <main>
      <MTitle class="title">
        <template #left>
          订单信息
        </template>
      </MTitle>
      <form>
        <table id="attributeTable" class="mtable">
          <tr class="mtr">
            <td class="field">订单编号</td>
            <td class="value">
              <MInput v-model="ProductInfo[0]" style="font-size: 12px;width: 100%" disabled></MInput>
            </td>
          </tr>
          <tr class="mtr">
            <td class="field">产品型号</td>
            <td class="value">
              <MSelect v-model="ProductInfo[1]" :options="TVOptions" :value="ProductInfo[1]" id="ruletype" required
                style="flex: 1 1 200px;width: 100%;" @change="optionChange">
              </MSelect>
            </td>
          </tr>
          <tr class="mtr">
            <td class="field">单价</td>
            <td class="value">
              <MInput v-model="ProductInfo[2]" style="font-size: 12px;width: 100%" disabled></MInput>
            </td>
          </tr>
          <tr class="mtr">
            <td class="field">数量</td>
            <td class="value">
              <MInput v-model="ProductInfo[3]" style="font-size: 12px;width: 100%" @change="numChange">
              </MInput>
            </td>
          </tr>
          <tr class="mtr">
            <td class="field">总价</td>
            <td class="value">
              <MInput v-model="ProductInfo[4]" style="font-size: 12px;width: 100%" disabled></MInput>
            </td>
          </tr>

        </table>
      </form>
      <MTitle class="title">
        <template #left>
          采购方信息
        </template>
      </MTitle>
      <form>
        <table id="attributeTable" class="mtable">
          <tr v-for="(obj, index) in MListItem1" :key="index" class="mtr">
            <td class="field">{{ obj.field }}</td>
            <td class="value" v-if="String(obj.field) != '验收标准' && String(obj.field) != '交货周期'">
              <MInput v-model="ProductInfo1[index]" style="font-size: 12px;width: 100%" :disabled="obj.disabled">
              </MInput>
            </td>
            <td class="value" v-if="String(obj.field) == '交货周期'">
              <MSelect v-model="ProductInfo1[index]"
                :options="[{ value: '一周', text: '一周' }, { value: '二周', text: '二周' }, { value: '三周', text: '三周' }, { value: '四周', text: '四周' }]"
                :value="ProductInfo1[index]" id="ruletype" required style="flex: 1 1 200px;width: 100%;">
              </MSelect>
            </td>
            <td class="value" v-if="String(obj.field) == '验收标准'" style="height:80px">
              <textarea v-model="ProductInfo1[index]" required
                style="width: 100%;border:1px solid #d2d2d2;border-radius: 5px;resize: none;padding: 5px;box-sizing: border-box;font-size: 12px;"
                rows="5">
        </textarea>
            </td>
          </tr>
        </table>
      </form>

    </main>
    <footer>
      <div style="text-align: center;" v-if="!isDisable">
        <MButton @click="applyOrder">确认下单</MButton>
      </div>
    </footer>
    <MMessage v-if="toastVisible" :message="toastMessage" :state="toastState" />

  </div>
</template>

<script>
import { ref, onMounted } from 'vue';
import MBreadcrumb from "../../components/MBreadcrumb.vue"
import MTitle from "../../components/MTitle.vue"
//import MList from "../../components/MList.vue"
import MButton from "../../components/MButton.vue"
import MInput from "../../components/MInput.vue"
import MMessage from '../../components/MMessage.vue';
import MSelect from '../../components/MSelect.vue';

//import MTag from "../../components/MTag.vue"
import axios from "../../axios/axios"
export default {
  name: "PartOrder",
  components: {
    MBreadcrumb,
    MTitle,
    MSelect,
    MButton,
    MInput,
    MMessage,
    //MTag
    //MIcon
  },
  setup() {
    const toastVisible = ref(false)
    const toastMessage = ref("")
    const toastState = ref("success")
    const breadcrumbItem = ref(
      {
        key: "0",
        title: '赋码管理',
        children: {
          key: "0-0",
          title: '采购下单',
        }
      })
    //const userId="12121"
    const MListItem = ref(
      [
        { "field": "订单编号", },
        { "field": "产品型号", },
        { "field": "单价", },
        { "field": "数量", },
        { "field": "总价", },
      ]
    )
    const MListItem1 = ref(
      [
        { "field": "公司名称", },
        { "field": "地址", },
        { "field": "联系人", },
        { "field": "联系电话", },
        { "field": "电子邮箱", },
        { "field": "交货周期", },
        { "field": "安装要求", },
        { "field": "验收标准", }
      ]
    )
    const ProductInfo = ref(["", "", "", 0, 0])
    const ProductInfo1 = ref(["", "", "", "", "", "", "", ""])
    const tagItems = ref([])
    const params = ref([])
    const userId = ref("")
    const TVList = ref([])
    const TVOptions = ref([])
    const isDisable = ref(false)
    const purchaseOrder = ref({})
    const numChange = () => {
      var data = [...ProductInfo.value]
      let numValue = parseFloat(data[3]);
      // 检查输入是否为数字且大于 0
      if (!isNaN(numValue) && numValue > 0) {
        console.log(purchaseOrder.value.goodsnumber == numValue);

        if (purchaseOrder.value.goodsnumber == numValue) {
          if (data[1] !== "") {
            data[4] = Number(TVList.value[data[1]].productprice) * Number(data[3])
          }
        } else {
          messageShow("采购数量应与电视数量相同", "warning")
        }

      } else {
        messageShow("数量应大于0", "warning")
        data[4] = 0
      }
      ProductInfo.value = data

    }
    const optionChange = () => {
      var data = [...ProductInfo.value]
      data[2] = TVList.value[data[1]].productprice
      if (Number(data[3]) > 0) {
        data[4] = Number(TVList.value[data[1]].productprice) * Number(data[3])
      } else {
        data[4] = 0
      }
      ProductInfo.value = data
    }
    const applyOrder = () => {
      if (chectValue()) {
        // console.log({
        //   userid: params.value.get('userId'),
        //   trainingid: params.value.get("trainingId"),
        //   ordernumber: ProductInfo.value[0],
        //   productmodel: TVOptions.value[Number(ProductInfo.value[1])].text,
        //   goodsprice: ProductInfo.value[2],
        //   goodsnumber: ProductInfo.value[3],
        //   totalprice: String(ProductInfo.value[4]),
        //   companyname: ProductInfo1.value[0],
        //   companyaddress: ProductInfo1.value[1],
        //   contactsname: ProductInfo1.value[2],
        //   contactsphone: ProductInfo1.value[3],
        //   contactsemail: ProductInfo1.value[4],
        //   deliverytime: ProductInfo1.value[5],
        //   installdemand: ProductInfo1.value[6],
        //   checkstandard: ProductInfo1.value[7],
        // });
        axios.post('/order/save', {
          userid: params.value.get('userId'),
          trainingid: params.value.get("trainingId"),
          ordernumber: ProductInfo.value[0],
          productmodel: TVOptions.value[Number(ProductInfo.value[1])].text,
          goodsprice: ProductInfo.value[2],
          goodsnumber: ProductInfo.value[3],
          totalprice: String(ProductInfo.value[4]),
          companyname: ProductInfo1.value[0],
          companyaddress: ProductInfo1.value[1],
          contactsname: ProductInfo1.value[2],
          contactsphone: ProductInfo1.value[3],
          contactsemail: ProductInfo1.value[4],
          deliverytime: ProductInfo1.value[5],
          installdemand: ProductInfo1.value[6],
          checkstandard: ProductInfo1.value[7],
          ispart: "1"
        })
          .then(response => {
            if (response.data.Code == "200") {
              messageShow("已下单", "success")
              ProductInfo1.value = ["", "", "", "", "", "", "", ""]
            } else {
              messageShow(response.data.Msg, "warning")
            }
          })
      }

    }
    const chectValue = () => {
      const hasEmpty = ProductInfo.value.some(function (item, index) {
        if (item === "") {
          messageShow("请输入" + MListItem.value[index].field, "warning");
          return true;
        }
        return false;
      });
      const hasEmpty1 = ProductInfo1.value.some(function (item, index) {
        if (item === "") {
          messageShow("请输入" + MListItem1.value[index].field, "warning");
          return true;
        }
        return false;
      });
      let numValue = parseFloat(ProductInfo.value[3]);
      // 检查输入是否为数字且大于 0
      if (!(!isNaN(numValue) && numValue > 0)) {
        messageShow("数量应大于0", "warning")
        return false
      }

      return !(hasEmpty || hasEmpty1);
    }
    const messageShow = (msg, state) => {
      toastMessage.value = msg;
      toastVisible.value = true;
      toastState.value = state
      // 使用 setTimeout 模拟 Toast 组件内部的定时器功能（仅用于演示）
      // 在实际使用中，你应该依赖 Toast 组件内部的定时器
      setTimeout(() => {
        toastVisible.value = false;
      }, 3000); // 与 Toast 组件中的 duration 属性保持一致
    }
    onMounted(() => {
      // 获取 URL 参数
      const param = new URLSearchParams(window.location.search);
      params.value = param
      if (param.has('userId')) {
        userId.value = param.get('userId');
      }
      if (param.has('isDisable')) {
        isDisable.value = param.get('isDisable') === "true"
      }
      axios.get('/order/number')
        .then(response => {
          var data = ProductInfo.value
          data[0] = response.data.Data
          ProductInfo.value = data
        })
      axios.get('/lcd/select')
        .then(response => {
          var info = response.data.Data

          var options = []
          for (var i = 0; i < info.length; i++) {
            options.push({ value: i, text: info[i].productmodel })
          }
          TVOptions.value = options
          TVList.value = info
        })
      axios.get('/apply/select?userId=' + params.value.get('userId') + "&trainingId=" + params.value.get('trainingId'))
        .then(response => {
          purchaseOrder.value = response.data.Data
        })

    });
    return {
      toastVisible,
      toastMessage,
      toastState,
      breadcrumbItem,
      MListItem,
      tagItems,
      ProductInfo,
      ProductInfo1,
      MListItem1,
      TVOptions,
      isDisable,
      applyOrder,
      optionChange,
      numChange
    };
  },
};
</script>

<style scoped>
.title {
  margin-top: 30px;
}

.title1 {
  margin-top: 20px;
}

.mtr {
  display: flex;
  flex-wrap: wrap;
  /* 允许子元素换行 */
  align-items: flex-start;
}

.container {
  display: flex;
  flex-direction: column;
  min-height: 100vh;
}

footer {
  text-align: center;
  height: 10%;
}

main {
  flex: 1;
}

.mtable {
  width: 100%;
  font-size: 13px;

}

.field {
  text-align: left;
  padding: 4px 0;
  flex: 1 1 60px;
  word-break: break-word;
  /* 允许长单词换行 */
  overflow-wrap: break-word;
  min-width: 0;
  /* 确保内容可以缩小 */
  height: 26px;
  line-height: 26px;
}

.value {
  text-align: right;
  padding: 4px 0;
  flex: 1 1 190px;
  word-break: break-word;
  /* 允许长单词换行 */
  overflow-wrap: break-word;
  min-width: 0;
  height: 26px;
  line-height: 26px;
  /* 确保内容可以缩小 */
}
</style>
